package com.huan.ddl;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

import java.io.IOException;

//优化过后的判断表是否存在的实例
public class OptimizeAPI {

    //创建上下文对象
    private static Configuration conf ;
    //创建Hbase连接池
    private static Connection conn = null;
    //创建 管理员
    private static Admin admin = null;


    //静态代码块,优先执行
    static {
        try {
            //创建上下文对象并连接hbase属性
            conf = HBaseConfiguration.create();
            conf.set( "hbase.zookeeper.quorum","Bigdata01,Bigdata02,Bigdata03" );
            //连接池调用工厂连接类
            conn = ConnectionFactory.createConnection( conf );
            //用连接池获取hbase的管理员
            admin = conn.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //方法区
    public static boolean isTableExist(String tableName) throws IOException {

        /**
         * 用管理员调用此表是否存在  调用tableExists同时在源码可见添加TableName参数,
         * 将参数传递即可,并返回exists对象
         */
        boolean exists = admin.tableExists( TableName.valueOf( tableName ) );


        return exists;
    }

    public static void close(){
            try {
                //如果管理员不等于空则关闭资源
                if(admin != null) {
                    admin.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                //如果连接不等于空则关闭连接
                if(conn != null){
                    conn.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
    }


    public static void main(String[] args) throws IOException {

        boolean exist = isTableExist( "student" );
        System.out.println(exist);
        //关闭资源
        close();
    }

}
